<template>
  <el-drawer :visible.sync="visible" :title="title" :modal-append-to-body="true" :append-to-body="true"
    :destroy-on-close="false" :modal="true" direction="rtl" :wrapperClosable="false" custom-class="form-drawer"
    size="450px" @closed="closed">
    <div class="form-drawer__content">
      <table class="terminal-box">
        <tr>
          <td>客户姓名:</td>
          <td>{{terminal.name}}</td>
        </tr>
        <tr>
          <td>客户电话:</td>
          <td>{{terminal.phone}}</td>
        </tr>
        <tr>
          <td>客户单位:</td>
          <td>{{terminal.orgName}}</td>
        </tr>
      </table>
      <el-divider></el-divider>
      <div style="padding: 10px;">

        <div class="list-header">
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="grid-content bg-purple">子账号列表</div>
            </el-col>
            <!-- <el-col :span="8">
              <div class="grid-content bg-purple" style="text-align: right;">
                <el-button type="success" size="small" @click="submitForm">提交</el-button>
              </div>
            </el-col> -->
          </el-row>
        </div>
        <el-form ref="ruleForm" :model="form">
          <el-table :data="form.tableData" :show-header="true" border @cell-click="cellclick"
            :cell-class-name="cellClassName" style="width: 100%">
            <el-table-column prop="phone" label="手机号">
              <template slot-scope="scope">
                <el-form-item :prop="'tableData.'+scope.$index+'.phone'" :rules="rules.phone">
                  <el-input :ref="'phone_'+scope.$index" type="text" v-model="scope.row.phone"
                    v-show="scope.row.iseditor" @keyup.native.enter="blurClick(scope)" @blur="blurClick(scope)" />
                  <el-input v-show="!scope.row.iseditor" type="text" v-model="scope.row.phone" disabled />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column prop="name" label="姓名">
              <template slot-scope="scope">
                <el-form-item :prop="'tableData.'+scope.$index+'.name'" :rules="rules.name">
                  <el-input :ref="'name_'+scope.$index" type="text" v-model="scope.row.name" v-show="scope.row.iseditor"
                    @keyup.native.enter="blurClick(scope)" @blur="blurClick(scope)" />
                  <el-input v-show="!scope.row.iseditor" type="text" v-model="scope.row.name" disabled />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column prop="handle" align="center">
              <template slot="header" slot-scope="scope">
                <el-tooltip content="添加" placement="top" effect="light">
                  <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addRow" :loading="loading">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="提交" placement="bottom" effect="light" :hide-after="3000">
                  <el-button type="success" plain size="mini" icon="el-icon-upload2" @click="submitForm"></el-button>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="del(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
  </el-drawer>
</template>

<script>
  import {
    findSubList,
    saveSubUserBatch,
    getUserRoleIdsById
  } from '@/api/system/user'
  import {
    isOk
  } from '@/utils/request'
  export default {
    name: 'SubAccountDrawer',
    components: {},
    props: {
      properties: {
        type: Object,
        default: () => ({})
      }
    },
    computed: {},
    watch: {
      properties: {
        handler: function(value) {
          this.visible = value.visible
          if (value.data) {
            this.terminal.id = value.data.id || ''
            this.terminal.name = value.data.name || ''
            this.terminal.phone = value.data.phone || ''
            this.terminal.orgName = value.data.orgName || ''

            this.form.tableData.unshift({
              id: '',
              name: '',
              phone: '',
              orgId: value.data.id || '',
            })
          }
        },
        immediate: true,
        deep: false
      }
    },
    data() {
      var checkPhone = (rule, value, callback) => {
        let regName = /^[1]([3-9])[0-9]{9}$/;
        if (!value) {
          return callback(new Error('手机号不能为空'));
        } else {
          let reg = /(?<=tableData.).+(?=.phone)/;
          if (this.form.tableData.length > 1) {
            let matchResult = rule.field.match(reg);
            let index = 0
            if (matchResult.length > 0) {
              index = matchResult[0]
            }
            for (var i = 0; i < this.form.tableData.length; i++) {
              if (index != i && value == this.form.tableData[i].phone) {
                return callback(new Error('手机号码不能重复！'));
              }
            }
          }
          if (!regName.test(value)) {
            return callback(new Error('请输入正确的手机号'));
          }
          return callback();
        }
      };
      var checkName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('姓名不能为空'));
        } else {
          callback();
        }
      };
      return {
        visible: false,
        title: '子账号管理',
        loading: false,
        userRoles: null,
        terminal: {
          id: '',
          name: '',
          phone: '',
          orgName: ''
        },
        form: {
          tableData: []
        },
        rules: {
          name: [{
            required: true,
            trigger: 'blur',
            validator: checkName
          }],
          phone: [{
            required: true,
            trigger: 'blur',
            validator: checkPhone
          }]
        }
      }
    },
    created() {
      this.load();
      this.getUserRoleIdsById();
    },
    methods: {
      load() {
        this.loading = true
        findSubList({
            orgId: this.terminal.id,
          }).then(rsp => {
            if (isOk(rsp)) {
              const _data = rsp.result
              this.form.tableData = _data
              this.loading = false
            }
          }).catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.loading = false
          })
      },
      getUserRoleIdsById() {
        getUserRoleIdsById({
            userId: this.terminal.id
          }).then(response => {
            if (isOk(response)) {
              this.userRoles = response.result;
            }
          }).catch(err => {
            console.log(err);
          })
          .finally(() => {})
      },
      addRow: function() {
        this.form.tableData.unshift({
          id: '',
          name: '',
          phone: '',
          orgId: this.terminal.id || ''
        })
      },
      cellclick: function(row, column) {
        console.log();
        if (column.label === '姓名') {
          this.$set(row, 'iseditor', true)
        }
        if (column.label === '手机号') {
          this.$set(row, 'iseditor', true)
        }
        if (column.property != 'handle') {
          this.$nextTick(() => {
            this.$refs[column.property + '_' + row.index].focus()
          })
        }
      },
      blurClick({
        row,
        column
      }) {
        if (column.label === '姓名') {
          this.$set(row, 'iseditor', false)
        }
        if (column.label === '手机号') {
          this.$set(row, 'iseditor', false)
        }
      },
      cellClassName({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        row.index = rowIndex;
        column.index = columnIndex;
      },
      submitForm() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.$confirm('提交后数据将会被更新，确认提交吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.loading = true
              saveSubUserBatch({
                  users: this.form.tableData,
                  orgId: this.terminal.id,
                  roleIds: this.userRoles != null && this.userRoles != '' && this.userRoles != undefined ?
                    this.userRoles.join() : ''
                }).then(rsp => {
                  this.$message({
                    type: 'success',
                    message: '保存成功'
                  })
                  //this.closed()
                }).catch(err => {
                  console.log(err);
                })
                .finally(() => {
                  this.loading = false
                })
            })
          } else {
            this.loading = false
            return false;
          }
        })
      },
      del(index) {
        this.form.tableData.splice(index, 1);
        // this.$refs.ruleForm.validate()
      },
      closed: function() {
        this.$emit('closed', false)
      },
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #aaaaaa;
  }

  /deep/ .el-dialog__body {
    padding: 0px 0px;
  }

  /deep/.el-dialog__footer {
    padding: 10px;
    padding-top: 10px;
    border-top: 1px solid #aaaaaa;
  }

  /deep/.el-drawer__header {
    padding: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #aaaaaa;
    font-weight: bold;
    font-size: 1rem;
    margin-bottom: 0.625rem;
    color: #333333;
  }

  .list-header {
    border-left: 5px solid #02a7f0;
    padding-left: 5px;
    line-height: 30px;
    height: 30px;
    font-size: 16px;
    font-weight: bold;
    color: #333333;
    margin-bottom: 10px;
  }

  /deep/.el-divider {
    margin-top: 10px;
    margin-bottom: 0px;
  }

  /deep/.terminal-box {
    font-size: 14px;
    padding-left: 10px;
    border-collapse: separate;
    border-spacing: 0px 15px;

    >tr {
      td:first-child {
        width: 70px;
        font-weight: bold;
        color: #99a9bf;
      }

      td:last-child {
        font-weight: bold;
      }
    }
  }

  /deep/.el-input.is-disabled .el-input__inner {
    background-color: #ffffff;
    border-color: #ffffff;
    color: #606266;
    cursor: not-allowed;
  }

 /deep/ .el-input.is-disabled:hover {
    background-color: #F5F7FA;
  }

  /deep/.el-tooltip__popper {
    line-height: 0.1;
  }
</style>
